<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: GetCircle.php
 * Date: 2017/1/2
 * Time: 23:13
 */

namespace app\api\model\page\circle;

use app\api\model\dao\Circle;
use app\api\model\dao\CircleStatistics;
use app\api\model\dao\Note;
use app\api\model\dao\UserAccount;
use app\api\model\dao\UserFavorite;
use app\library\Error;
use app\library\Flag;
use app\library\PageBase;
use think\Validate;
use think\Exception;

class GetCircleInfo extends PageBase
{

    private $objCircle;
    private $objUserAccount;
    private $objCircleStatistics;
    private $objNote;
    private $objUserFavorite;

    public function __construct()
    {
        parent::__construct();

        $this->objCircle = new Circle();
        $this->objUserAccount = new UserAccount();
        $this->objCircleStatistics = new CircleStatistics();
        $this->objNote = new Note();
        $this->objUserFavorite = new UserFavorite();

    }

    /**
     * @param $param
     * @return array|bool
     * @DESC 验证接口字段
     */
    public function checkParam($param)
    {
        $rule = [
            'cir_id' => 'require',
        ];
        $msg = [
            'cir_id.require' => '参数缺少圈子ID',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return '';
    }

    /**
     * page 入口
     *
     * @param $param
     * @return array
     * @throws Exception
     */
    public function myExcute($param)
    {
        $this->checkToken($param);

        $this->user_id = !empty($this->user_id) ? $this->user_id : 0;

        // 1、参数校验
        $ret = $this->checkParam($param);
        if ($ret) {
            throw new Exception($ret, Error::ERR_PARAM);
        }

        // 2、从数据库中获取圈子详情
        $ret = $this->getCircleInfoFromDB($param['cir_id']);
        if (false === $ret) {
            throw new Exception('get circle info from db fail. [circle_id: ' . $param['cir_id'] . ']', Error::ERR_SYS);
        }

        if (empty($ret)) {
            throw new Exception('circle is empty. [circle_id: ' . $param['cir_id'] . ']', Error::ERR_CIRCLE_NOT_EXIST);
        }

        // 3、校验是否被删除
        if (Flag::CONST_CIRCLE_DELETED == $ret['is_delete']) {
            throw new Exception('circle is deleted', Error::ERR_CIRCLE_DELETED);
        }

        // 4、校验是否审核
        if (Flag::CONST_CIRCLE_APPROVE_PASS != $ret['approve_status']) {
            throw new Exception('circle is not approve', Error::ERR_CIRCLE_APPROVE_NOT);
        }

        // 5、获取创建者信息
        $user_account = $this->objUserAccount->getUserAccount(['user_id' => $ret['creator']]);
        if (false === $user_account) {
            throw new Exception('get user account from db fail. [user_id: ' . $ret['creator'] . ']', Error::ERR_SYS);
        }

        // 6、获取人物排行
        $photos = $this->getPeopleRank($ret['id']);

        $this->data = $this->composeData($ret, $user_account[0], $photos);

        $this->objCircleStatistics->addCircleStatistics(['cir_id' => $ret['id'], 'userid' => $this->user_id]);

    }

    /**
     * 从数据库中获取圈子详情
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getCircleInfoFromDB($cir_id)
    {
        if (!$cir_id) {
            return false;
        }
        $arrCond = [
            'id' => ['=', $cir_id]
        ];
        $ret = $this->objCircle->getCircle($arrCond);
        if (false === $ret) {
            return false;
        }
        $ret = $ret[0];
        return $ret;
    }

    /**
     * 获取人物排行
     *
     * @param $cir_id
     * @return bool|false|\PDOStatement|string|\think\Collection
     */
    public function getPeopleRank($cir_id)
    {
        if (!$cir_id) {
            return false;
        }

        $ret = $this->objNote->getNoteRankByCirid($cir_id);
        if (empty($ret)) {
            return [];
        }

        $userid2cnt = [];

        foreach ($ret as $val) {
            $userid2cnt[$val['creator']] = $val['note_cnt'];
        }

        $photos = [];

        if (!empty($userid2cnt)) {
            $userid2photo = [];
            $rank_user_account = $this->objUserAccount->getUserAccountByUserids(array_keys($userid2cnt));
            if (!empty($rank_user_account)) {
                foreach ($rank_user_account as $val) {
                    $userid2photo[$val['id']] = $val['avatar'];
                }
            }
            if ($userid2photo) {
                foreach ($userid2cnt as $userid => $val) {
                    $photos[$userid] = $userid2photo[$userid];
                }
            }
        }

        return $photos;
    }

    public function composeData($circle_info, $user_account, $photos)
    {

        // 获取圈子总人数
        $fav_user_cnt = $this->objUserFavorite->getFavoriteCountByType(Flag::CONST_FOLLOW_CIRCLE);
        empty($fav_user_cnt) && $fav_user_cnt = 0;

        // 获取总帖子数
        $conds = [
            'cir_id' => ['=', $circle_info['id']],
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        $note_cnt = $this->objNote->getNoteCount($conds);
        empty($note_cnt) && $note_cnt = 0;

        // 获取今天的帖子数
        $conds = [
            'cir_id' => ['=', $circle_info['id']],
            'date' => ['=', date('Ymd')],
            'is_delete' => ['=', Flag::CONST_NOTE_DELETE_NOT]
        ];
        $note_today_cnt = $this->objNote->getNoteCount($conds);
        empty($note_today_cnt) && $note_today_cnt = 0;

        $data = [];
        $data['creator'] = [
            'nickname' => $user_account['nick_name'],
            'userid' => $circle_info['creator'],
            'photo' => $user_account['avatar'],
        ];
        $data['circle'] = [
            'name' => $circle_info['name'],
            'create_time' => $circle_info['create_time'],
            'people_num' => $fav_user_cnt,
            'note_num' => $note_cnt,
            'today_note_num' => $note_today_cnt,
            'briefing' => $circle_info['briefing'],
            'announcement' => $circle_info['announcement'],
        ];
        foreach ($photos as $key => $val) {
            $data['people_rank'][] = [
                'userid' => $key,
                'photo' => $val,
            ];
        }

        return $data;
    }
}
